<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar
      title="标题"
      right-text="搜索"
      left-arrow
      @click-left="$router.back()"
      @click-right="search(value)"
    >
      <template #title>
        <van-search
          v-model.trim="value"
          shape="round"
          placeholder="请输入搜索关键词"
          @focus="isResultShow = false"
        />
      </template>
    </van-nav-bar>

    <!-- 搜索结果 -->
    <SearchResult v-if="isResultShow" :value="value" />

    <!-- 联想建议 -->
    <SearchSuggest
      v-else-if="value"
      :value="value"
      @suggestClick="search($event)"
    />

    <!-- 搜索历史 -->
    <SearchHistory
      v-else
      :history="history"
      @delAllHistory="delAllHistory"
      @delHistory="delHistory"
      @searchs="search($event)"
    />
  </div>
</template>

<script>
import SearchResult from './components/search-result.vue'
import SearchSuggest from './components/search-suggest.vue'
import SearchHistory from './components/search-history.vue'

export default {
  name: 'SearchIndex',
  data () {
    return {
      value: '',
      isResultShow: false, // 控制搜索结果
      history: JSON.parse(localStorage.getItem('history')) || []
    }
  },
  components: {
    SearchResult,
    SearchSuggest,
    SearchHistory
  },
  methods: {
    search (val) {
      this.value = val
      if (this.value === '') {
        return
      }
      this.isResultShow = true
      // 判断是否重复
      const i = this.history.findIndex((item) => item === val)
      if (i !== -1) {
        this.history.splice(i, 1)
      }
      this.history.unshift(val)
      localStorage.setItem('history', JSON.stringify(this.history))
    },

    // 删除单个历史记录
    delHistory (i) {
      this.history.splice(i, 1)
      localStorage.setItem('history', JSON.stringify(this.history))
    },

    // 删除所有历史记录
    delAllHistory () {
      this.history = []
      localStorage.removeItem('history')
    }
  }
}
</script>

<style scoped lang="scss">
.search {
  ::v-deep.van-nav-bar__title {
    max-width: unset;
  }
  .van-search {
    padding: 0;
    width: 240px;
  }
}
</style>
